package workexp.alg.question;

import java.util.LinkedList;
import java.util.Queue;

public class FloodFill {

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        /**
         * 上下左右，四个接邻块，X+1,y+1,x-1,y-1;
         */
        int[] dx = {1, 0, 0, -1};
        int[] dy = {0, 1, -1, 0};
        //n=x,m=y
        int n = image.length, m = image[0].length;
        int oldcolor = image[sr][sc];
        if(oldcolor==newColor){
            return image;
        }
        //广度优先
        Queue<int[]> queue = new LinkedList<int[]>();
        queue.offer(new int[]{sr, sc});
        image[sr][sc] = newColor;
        while(!queue.isEmpty()){
            int[] cell = queue.poll();
            int x = cell[0];
            int y = cell[1];
            for (int i = 0; i < 4 ; i++) {
                int mx=x+dx[i];
                int my=y+dy[i];
                //新xy不为附属，不超边界
                if(mx>=0 && mx<n && my>=0 && my<m && image[mx][my] == oldcolor){
                    queue.offer(new int[]{mx, my});
                    image[mx][my] =newColor;
                }

            }
        }

        return image;
    }

//dfs
/*    class Solution {
        int[] dx = {1, 0, 0, -1};
        int[] dy = {0, 1, -1, 0};

        public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
            int currColor = image[sr][sc];
            if (currColor != newColor) {
                dfs(image, sr, sc, currColor, newColor);
            }
            return image;
        }

        public void dfs(int[][] image, int x, int y, int color, int newColor) {
            if (image[x][y] == color) {
                image[x][y] = newColor;
                for (int i = 0; i < 4; i++) {
                    int mx = x + dx[i], my = y + dy[i];
                    if (mx >= 0 && mx < image.length && my >= 0 && my < image[0].length) {
                        dfs(image, mx, my, color, newColor);
                    }
                }
            }
        }
    }*/


}
